//
//  HRTextView.swift
//  weiBo
//
//  Created by helong on 16/7/18.
//  Copyright © 2016年 helong. All rights reserved.
//

import UIKit
/// 自定义textView
class HRTextView: UITextView {

    //  占位文字
    var placeholderText: String? {
        didSet{
            placeholderLabel.text = placeholderText
        }
    }
    //  懒加载placeholder
    private lazy var placeholderLabel: UILabel = {
        
    let lbl = UILabel(textColor: UIColor.grayColor(), fontSize: 14)
        lbl.numberOfLines = 0
        lbl.text = "听说下雨天音乐跟辣条更配哟~"
        lbl.sizeToFit()
        return lbl

    }()
    
   
    //  重写textView的font属性
    override var font: UIFont?{
        didSet{
            if font == nil {
                return
            }
            placeholderLabel.font = font
        }
    }
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   // MARK: -  设置UI相关
    private func setupUI(){
        
//        self.delegate = self//这里不要用代理,外面已经用过代理了
        backgroundColor = UIColor.whiteColor()
        addSubview(placeholderLabel)//添加占位label
        
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        
       addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 8))
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
    }
    
     // MARK: - 监听文本框的文字改变的通知
   @objc private func textChange() {
        if self.hasText() {
            placeholderLabel.text = nil
            placeholderLabel.hidden = true
        }else {
            placeholderLabel.text = placeholderText
            placeholderLabel.hidden = false
        }
    }

    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
